/**
 * 
 */
package com.nari.baseinfo.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;

import com.nari.baseinfo.model.ICommunity;
import com.nari.coreframe.dao.hibernate3.GenericDaoImpl;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResponseMsg;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.rescontroller.dao.IResourceAccessControlDao;

/**
 * 
 * @author Xiaopeng
 * @date 2013-8-1
 */
public class CommunityDaoImpl extends GenericDaoImpl<ICommunity, String> implements ICommunityDao {
	private IResourceAccessControlDao iResourceAccessControlDao;
	
	/**
	 * 根据小区所属信息（所属三级机构、所属项目等）查询小区列表
	 * @param provinceCityID 所属省级机构
	 * @param capitalCityID 所属市级机构
	 * @param districtCityID 所属区级机构
	 * @param projectUID 所属项目
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-25
	 */
	public List<ICommunity> queryCommunitysByBelongings(String provinceCityID,
			String capitalCityID, String districtCityID, String projectUID) throws Exception {
		if (provinceCityID != null && !"".equals(provinceCityID.trim())
				|| (capitalCityID != null && !"".equals(capitalCityID.trim()))
				|| (districtCityID != null && !"".equals(districtCityID.trim()))
				|| (projectUID != null && !"".equals(projectUID.trim()))) {
			String listHql = "from ICommunity c where 1=1";
			// 所属省级机构
			if (provinceCityID != null && !"".equals(provinceCityID.trim())) {
				listHql += " and c.provinceCityID='" + provinceCityID.trim() + "'";
			}
			// 所属市级机构
			if (capitalCityID != null && !"".equals(capitalCityID.trim())) {
				listHql += " and c.capitalCityID='" + capitalCityID.trim() + "'";
			}
			// 所属区级机构
			if (districtCityID != null && !"".equals(districtCityID.trim())) {
				listHql += " and c.districtCityID='" + districtCityID.trim() + "'";
			}
			// 所属项目
			if (projectUID != null && !"".equals(projectUID.trim())) {
				listHql += " and c.projectID='" + projectUID.trim() + "'";
			}
			//权限资源匹配
			String authorityRes = iResourceAccessControlDao.queryAuthorityProjResHql();
			if(!"".equals(authorityRes)) {
				listHql += " and c.projectID in("+authorityRes+")";
			}
			listHql += " order by c.communityName asc";
			return this.runQueryHSql(listHql);
		}
		return new ArrayList<ICommunity>();
	}

	/**
	 * 分页查询小区信息
	 * @param communityName 小区名称(可选)
	 * @param provinceCityID 所属省级机构(可选)
	 * @param capitalCityID 所属市级机构(可选)
	 * @param districtCityID 所属区级机构(可选)
	 * @param projectUID 所属项目(可选)
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-25
	 */
	@SuppressWarnings("unchecked")
	public ResultWithPageCond<ICommunity> queryCommunityWithPageCond(String communityName, 
			String provinceCityID, String capitalCityID, String districtCityID, 
			String projectUID, PageCond pageCond) throws Exception {
		String listHql = "from ICommunity c where 1=1";
		// 小区名称
		if (communityName != null && !"".equals(communityName.trim())) {
			listHql += " and lower(c.communityName) like '%"+communityName.trim().toLowerCase()+"%'";
		}
		// 所属省级机构
		if (provinceCityID != null && !"".equals(provinceCityID.trim())) {
			listHql += " and c.provinceCityID='" + provinceCityID.trim() + "'";
		}
		// 所属市级机构
		if (capitalCityID != null && !"".equals(capitalCityID.trim())) {
			listHql += " and c.capitalCityID='" + capitalCityID.trim() + "'";
		}
		// 所属区级机构
		if (districtCityID != null && !"".equals(districtCityID.trim())) {
			listHql += " and c.districtCityID='" + districtCityID.trim() + "'";
		}
		// 所属项目
		if (projectUID != null && !"".equals(projectUID.trim())) {
			listHql += " and c.projectID='" + projectUID.trim() + "'";
		}
		//权限资源匹配
		String authorityRes = iResourceAccessControlDao.queryAuthorityProjResHql();
		if(!"".equals(authorityRes)) {
			listHql += " and c.projectID in("+authorityRes+")";
		}
		//统计结果集个数
		String countHql = "select count(*) " + listHql;
		int total = ((Long)this.getCurrentSession().createQuery(countHql).uniqueResult()).intValue();
		// 结果集排序
		listHql += " order by c.communityName asc";
		// 结果集分页
		Query listQuery = this.getCurrentSession().createQuery(listHql);
		listQuery.setFirstResult(pageCond.getStart()).setMaxResults(pageCond.getLimit());
		// 构造返回类型
		pageCond.setTotal(total);
		ResultWithPageCond<ICommunity> communityPage = new ResultWithPageCond<ICommunity>();
		communityPage.setList(listQuery.list());
		communityPage.setPageCond(pageCond);
		return communityPage;
	}

	/**
	 * 通过小区ID列表查询小区信息
	 * @param idList 小区ID列表，若列表为空，则返回空列表
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-13
	 */
	public List<ICommunity> queryCommunityByIDList(List<String> idList) throws Exception {
		if (idList != null && idList.size() > 0) {
			StringBuffer hsql = new StringBuffer("select distinct c from ICommunity c ");
			hsql.append("where c.id in(");
			for (int index = 0; index < idList.size(); index++) {
				hsql.append("'");
				hsql.append(idList.get(index));
				hsql.append("'");
				if (index < idList.size() - 1) {
					hsql.append(",");
				}
			}
			hsql.append(") ");
			hsql.append("order by c.communityName");
			return this.runQueryHSql(hsql.toString());
		}
		return null;
	}

	/**
	 * 通过小区ID列表查询小区ID-小区名称映射表
	 * @param idList 小区ID列表，若列表为空，则返回一个空映射表
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-13
	 */
	public Map<String, String> queryIdNameMapByIDList(List<String> idList) throws Exception {
		Map<String, String> idNameMap = new HashMap<String, String>();
		if (idList != null && idList.size() > 0) {
			StringBuffer hsql = new StringBuffer("select distinct c.id,c.communityName ");
			hsql.append("from ICommunity c ");
			hsql.append("where c.id in(");
			for (int index = 0; index < idList.size(); index++) {
				hsql.append("'");
				hsql.append(idList.get(index));
				hsql.append("'");
				if (index < idList.size() - 1) {
					hsql.append(",");
				}
			}
			hsql.append(")");
			List<Object> resultsList = this.runQueryHSqlObject(hsql.toString());
			// 格式化查询结果集
			if (resultsList != null && resultsList.size() > 0) {
				for (Object result : resultsList) {
					Object[] arrayMap = (Object[]) result;
					idNameMap.put(arrayMap[0].toString(), arrayMap[1].toString());
				}
			}
		}
		return idNameMap;
	}
	
	/**
	 * 通过小区所属关系统计小区的个数
	 * @param provinceCityUID 所属省级机构(可选)
	 * @param capitalCityUID 所属市级机构(可选)
	 * @param districtCityUID 所属区级机构(可选)
	 * @param projectUID 所属项目(可选)
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-10-21
	 */
	public int countCommunitySumByBelongs(String provinceCityUID, String capitalCityUID, 
			String districtCityUID, String projectUID) throws Exception {
		String countHql = "select count(*) from ICommunity c where 1=1";
		// 所属省级机构
		if (provinceCityUID != null && !"".equals(provinceCityUID.trim())) {
			countHql += " and c.provinceCityID='" + provinceCityUID.trim() + "'";
		}
		// 所属市级机构
		if (capitalCityUID != null && !"".equals(capitalCityUID.trim())) {
			countHql += " and c.capitalCityID='" + capitalCityUID.trim() + "'";
		}
		// 所属区级机构
		if (districtCityUID != null && !"".equals(districtCityUID.trim())) {
			countHql += " and c.districtCityID='" + districtCityUID.trim() + "'";
		}
		// 所属项目
		if (projectUID != null && !"".equals(projectUID.trim())) {
			countHql += " and c.projectID='" + projectUID.trim() + "'";
		}
		//权限资源匹配
		String authorityRes = iResourceAccessControlDao.queryAuthorityProjResHql();
		if(!"".equals(authorityRes)) {
			countHql += " and c.projectID in("+authorityRes+")";
		}
		// 统计结果集个数
		return ((Long)this.getCurrentSession().createQuery(countHql).uniqueResult()).intValue();
	}

	/**
	 * 根据小区ID级联删除关联信息
	 * 包括：小区、楼栋、单元、热用户、系统用户及角色、集中器、热量表、分配表、散热器、温度点、
	 * 分摊域、分摊域分摊账单、用户分摊账单
	 * 注意：热量表数据、分配表数据等表计数据具有不可恢复性，因此不能作为级联删除的对象
	 * @param communityUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-20
	 */
	public ResponseMsg deleteCascadeByCommunityUID(String communityUID) throws Exception {
		//删除小区所属散热器
		String delSinkerHql = "delete from PSinkInfo sink " +
				"where sink.roomId in(select hr.id " +
									"from IHeatRoom hr " +
									"where hr.communityID='"+communityUID+"')";
		this.runFormatHSql(delSinkerHql);
		//删除小区所属分配表
		String delAssignMeterHql = "delete from IAssignMeter am " +
				"where am.roomId in(select hr.id " +
								"from IHeatRoom hr " +
								"where hr.communityID='"+communityUID+"')";
		this.runFormatHSql(delAssignMeterHql);
		//删除小区所属热量表
		String delHeatMeterHql = "delete from IHeatMeter hm " +
				"where hm.communityID='"+communityUID+"'";
		this.runFormatHSql(delHeatMeterHql);
		//删除小区所属分摊域
		String delShareAreaHql = "delete from IShareArea sa " +
				"where sa.communityID='"+communityUID+"'";
		this.runFormatHSql(delShareAreaHql);
		//删除小区所属分摊账单
		String delSinkResultHql = "delete from IShareSinkResult ssr " +
				"where ssr.userShareResultID in(select usr.id " +
											"from IUserShareResult usr " +
											"where usr.communityID='"+communityUID+"')";
		this.runFormatHSql(delSinkResultHql);
		String delUserResultHql = "delete from IUserShareResult usr " +
				"where usr.communityID='"+communityUID+"'";
		this.runFormatHSql(delUserResultHql);
		String delAreaResultHql = "delete from IShareAreaResult sar " +
				"where sar.communityID='"+communityUID+"'";
		this.runFormatHSql(delAreaResultHql);
		//删除小区所属楼栋单元
		String delUnitHql = "delete from IBuildingUnit bu " +
				"where bu.buildingID in(select b.id " +
				 					"from IBuilding b " +
				 					"where b.communityID='"+communityUID+"')";
		this.runFormatHSql(delUnitHql);
		//删除小区所属楼栋
		String delBuildingHql = "delete from IBuilding b " +
				"where b.communityID='"+communityUID+"'";
		this.runFormatHSql(delBuildingHql);
		//删除小区所属集中器
		String delConcentratorHql = "delete from IConcentrator c " +
				"where c.communityID='"+communityUID+"'";
		this.runFormatHSql(delConcentratorHql);
		//删除小区所属的温度点
		String delTempPointHql = "delete from ITemperaturePoint tp " +
				"where tp.communityID='"+communityUID+"'";
		this.runFormatHSql(delTempPointHql);
		//删除小区所属系统用户、用户角色
		String delUserRoleHql = "delete from IUserRole ur " +
				"where ur.userUuid in(select u.id " +
									"from IUser u " +
									"where u.roomId in(select hr.id " +
													"from IHeatRoom hr " +
													"where hr.communityID='"+communityUID+"'))";
		this.runFormatHSql(delUserRoleHql);
		String deleteUserHql = "delete from IUser u " +
				"where u.roomId in(select hr.id " +
								"from IHeatRoom hr " +
								"where hr.communityID='"+communityUID+"')";
		this.runFormatHSql(deleteUserHql);
		//删除小区所属热用户
		String delRoomHql = "delete from IHeatRoom hr " +
				"where hr.communityID='"+communityUID+"'";
		this.runFormatHSql(delRoomHql);
		//删除小区信息
		this.deleteEntityById(communityUID);
		return ResponseMsg.getInstance(true, "");
	}

	/**
	 * @return the iResourceAccessControlDao
	 */
	public IResourceAccessControlDao getiResourceAccessControlDao() {
		return iResourceAccessControlDao;
	}

	/**
	 * @param iResourceAccessControlDao the iResourceAccessControlDao to set
	 */
	public void setiResourceAccessControlDao(
			IResourceAccessControlDao iResourceAccessControlDao) {
		this.iResourceAccessControlDao = iResourceAccessControlDao;
	}
	
}
